<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2020 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\cms\controller;


use function PHPSTORM_META\type;
use think\admin\Controller;
use think\facade\Config;
use think\admin\service\AdminService;
use think\admin\extend\DataExtend;
use think\admin\service\MenuService;




/**
 * 企业经营不良行为
 * Class Qiyestain
 * @package app\wechat\controller
 */
class Qiyestain extends BaseController
{

    /**
     * 当前操作数据库
     * @var string
     */
    protected $table = 'CmsQiyeAccident';
    protected $acc_type = "stain";

    /**
     * 企业污点台账管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {

        $this->title = "经营不良行为";
        $map = ["type"=>$this->acc_type,'is_deleted' => '0'];

        //根据like后的字段来进行搜索
        $name = $this->request->get("qiye");
        $qiye_ids = $this->_query_data_ids($name, "CmsQiye");
        $this->type = $this->acc_type;
        $query = $this->_query($this->table)->like('name')->whereIn("qiye_id",$qiye_ids)
            ->where($map)->order('id desc');
        $query->whereNotIn('id', ['subscribe', 'default'])->order('id desc')->page();

    }

    public function _query_data_ids($name, $tableName){
        $query = $this->app->db->name($tableName)->whereLike('name',"%".$name."%")
            ->field("id")->order('id desc')->select();
        $ids = array();
        for($i=0; $i<count($query); $i++){
            $ids[] = $query[$i]['id'];
        }
        return $ids;
    }

    /**
     * 数据列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _index_page_filter(&$data)
    {
        $qiye_ids = $this->_getDataIds($data, "qiye_id");
        $qiye = $this->_getQiyeDict($qiye_ids);
        for($i=0; $i<count($data); $i++){
            $data[$i]['qiye_info'] = $qiye[$data[$i]['qiye_id']];
            $data[$i]['pics'] = explode(",",$data[$i]['annex']);
        }
    }


    /**
     * 表单数据处理
     * @param array $vo
     * @throws \ReflectionException
     */
    protected function _form_filter(&$vo)
    {

        if ($this->request->isGet()) {
            AdminService::instance()->clearCache();
            if($vo && $vo['qiye_id'])
                $map = array("id"=>$vo['qiye_id']);
            else
                $map = array();
            $this->qiye = $this->app->db->name("CmsQiye")->where($map)->find();

        }

    }

    /**
     * 添加经营不良行为
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function add()
    {

        if ($this->request->isGet()) {
            $this->_applyFormToken();
            $this->_form($this->table, 'form');
        } else {

            $update = $this->request->post('data', []);
            $update[ 'create_by']   = AdminService::instance()->getUserId();
            $update[ 'update_at'] = $update[ 'create_at'] = time();
            $update[ 'type'] = "stain";
            if ($this->app->db->name($this->table)->insert($update) !== false) {
                $this->success('添加成功！','javascript:history.back()');
            } else {
                $this->error('添加失败，请稍候再试！');
            }
        }
    }

    /**
     * 编辑经营不良行为
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {

        $this->id = $this->request->get('id');
        $map = array("id" => $this->id);
        if (empty($this->id)) $this->error('参数错误，请稍候再试！');
        if ($this->request->isGet()) {
            if ($this->request->get('output') === 'json') {
                $this->success('获取数据成功！', $this->app->db->name($this->table)->where($map)->find());
            } else {
                $this->title = '编辑企业信息';
                $this->_applyFormToken();
                $this->_form($this->table, 'form');
            }
        }else{
            $data = $this->request->post('data', []);
            $data['update_at'] = time();
            if ($this->app->db->name($this->table)->where($map)->update($data) !== false) {
                $this->success('企业信息更新成功！', 'javascript:history.back()');
            } else {
                $this->error('企业信息更新失败，请稍候再试！');
            }
        }

    }

    protected function _getDataIds($data, $key){
        $arr = [];
        for ($i=0; $i<count($data); $i++){
            array_push($arr, $data[$i][$key]);
        }
        return $arr;
    }

    protected function _getQiyeDict($qiye_ids){
        $map = array("id"=> $qiye_ids);
        $class = $this->app->db->name('CmsQiye')->field("id,name,type,scale")->where($map)->select();
        $result = array();
        for ($i=0; $i<count($class); $i++){
            $result[$class[$i]['id']] = $class[$i];
        }
        return $result;
    }

    /**
     * 删除经营不良行为
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
        $this->_delete($this->table);
    }

}
